<html>
	<head><title>CS143 Project 1B Demo</title></head>
	<body>
		<p> TA: Please do not "TEST" your (especially, complicated) quries in this demo website. The loading of quries might kill the server. 
		Also, the machine running this website a has VERY different setting from your virutal machine, for example, the memory size, so testing your quries in this page is meaningless. 
		Since we grade your projects in a virtual machine. Please test your queries (especially queries with sub-queries) at your own machine. </p>
		Type an SQL query in the following box:
		<p>
		
		<form method="GET">
		<textarea name="query" cols="60" rows="8"><?php if (isset($_REQUEST['query'])){echo $_REQUEST['query'];}?></textarea>
		<input type="submit" value="Submit" />
		</form>
		</p>
		<p><small>Note: tables and fields are case sensitive. Run "show tables" to see the list of
		available tables.</small>
		</p>

		<?php 
		//ini_set('display_errors','On');
		//error_reporting(E_ALL);

		$db_connection = mysql_connect("localhost", "cs143", ""); // Create connection
		if(!$db_connection) {
			print "Connection failed";
			exit(1);
		}
		mysql_select_db("CS143", $db_connection);
		
		if (!isset($_REQUEST["query"])){ //Make sure query exists
			exit();
		}
		echo "<h3>Results from MySQL:</h3>"; 
		$query = $_REQUEST['query'];
		$rs = mysql_query($query, $db_connection); // Get result set

		if (!$rs) {
			die('Query failed: ' . mysql_error());
		}
		?>
		
		
		<table border=1 cellspacing=1 cellpadding=2>
		<?php
		
		echo "<tr align=center>";
		for($i = 0; $i < mysql_num_fields($rs); $i++){
			echo "<td><b>" . mysql_field_name($rs,$i) . "</b></td>"; // Output field headers in table
		}
		echo "</tr>";
		
		while($row = mysql_fetch_row($rs)) {
			echo "<tr align=center>";
			for ($j = 0; $j < count($row); $j++){
				echo "<td>" . $row[$j] . "</td>"; // Output the table values
			}
			echo "</tr>";
		}
		?>
		</table><?php

		mysql_close($db_connection);
		?><br />
	</body>
</html>
